<template>
  <base-window class-name="task-material-apply-dialog" ref="paasIframeWindow" :title="title" :size="size" :show.sync="visible" @closed="handleClose">
    <div class="paas-iframe-containner" v-loading="loading">
      <iframe
        id="paasIframe"
        :src="iframeUrl"
        @load="paasIframeOnLoad"
        frameborder="0"
        width="100%"
        height="100%"
      />
    </div>
  </base-window>
</template>

<script>
export default {
  name: 'task-material-apply-dialog',
  props: {
    appId: {
      type: String,
      default: ''
    },
    formId: {
      type: String,
      default: ''
    },
    task: {
      type: Object,
      default: () => ({})
    },
    formContentId: {
      type: String,
      default: ''
    },
    processorInstanceId: {
      type: String,
      default: ''
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      visible: false,
      title: '',
      size: 'larger'
    }
  },
  computed: {
    iframeUrl() {
      let url = ''
      this.isDetail
        ? url = `/paas/#/template/detail?formId=${this.formId}&formContentId=${this.formContentId}&processId=${this.processorInstanceId}` 
        : url = `/paas/#/template/edit?appId=${this.appId}&formId=${this.formId}`
      return url
    }
  },
  watch: {
    iframeUrl() {
      this.$nextTick(()=> {
        document.getElementById('paasIframe').contentWindow.location.reload(true)
      })
    }
  },
  mounted() {
    window.addEventListener('message', ({ data }) => {
      // 监听到子页面关闭
      if(data?.close) {
        this.visible = false;
        this.$emit('success');
      }

      if(data?.refresh) this.$emit('success');

      // 监听子页面加载完
      if (data?.ready) {
        // 发送工单数据
        let iframe = document.getElementById('paasIframe').contentWindow;
        iframe.postMessage({ task: this.task }, '*');

        this.loading = false;
      }
    })
  },
  methods: {
    /* 打开弹窗 */
    open(title) {
      this.title = title;
      title.includes(this.$t('common.base.addModule', {module: ''})) ? this.size = 'large' : this.size = 'larger'
      if(!this.iframeIsLoaded) this.loading = true
      this.visible = true;
      this.$nextTick(()=> {
        this.$refs.paasIframeWindow.showBaseWindow && this.$refs.paasIframeWindow.restoreWindow()
      })
    },
    paasIframeOnLoad() {
      this.loading = false;
      this.iframeIsLoaded = true
    },
    handleClose() {
      this.iframeIsLoaded = false
    }
  }
}
</script>

<style lang="scss">
.task-material-apply-dialog {
  .base-window-content-body {
    height: 100% !important;
    padding: 0 !important;
    overflow: hidden !important;
  }

  .base-window-content-footer {
    display: none;
  }

  .paas-iframe-containner {
    width: 100%;
    height: 100%;
  }
}
</style>